﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizProxy.Models;
using NPoco;
using Creative85.Framework.Data;
using Creative85.Framework.Utilities;

namespace BizProxy
{
    public class KeyValueService
    {
        public static int Clear(bool isExpired)
        {
            var query = Db.Instance.DeleteMany<KeyValue>();
            if (isExpired)
            {
                query = query.Where(x => x.ExpiredTime < DateTime.Now);
            }
            return query.Execute();
        }
        public static List<KeyValue> Load()
        {
            var list = Db.Instance.Query<KeyValue>().ToList();
            return list;
        }

        public static KeyValue Get(string key)
        {
            var kv = Db.Instance.SingleById<KeyValue>(key);
            return kv;
        }
        public static void Set(string key, string value, DateTime expiredTime)
        {
            var kv = new KeyValue()
            {
                Key = key ?? string.Empty,
                Value = value ?? string.Empty,
                CreateTime = DateTime.Now,
                ExpiredTime = expiredTime
            };
            Db.Instance.Insert(kv);
        }
        public static void Update(string key, DateTime expiredTime)
        {
            var kv = new KeyValue()
            {
                Key = key ?? string.Empty,
                ExpiredTime = expiredTime
            };
            Db.Instance.Update(kv, x => x.ExpiredTime);
        }
        public static void Remove(string key)
        {
            Db.Instance.DeleteMany<KeyValue>().Where(x => x.Key == key).Execute();
        }
    }
}
